#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: xjx
@time: 2023/11/5 21:55 
@file: mlp_test.py
@project: nanchangproject
@describe: TODO
"""
import sys
import os
import time
import django
from django.db.models import QuerySet
import joblib

sys.path.append('../../')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nanchangproject.settings')
django.setup()  # 很关键的配置，必须先setup在导入models类

from drivinginfo.models import Drivinginfo

mlp_model = joblib.load('saved_model_mlp.pkl')  # 全局变量，可以使用，但是没用


def test():
    time1 = time.perf_counter()
    global mlp_model
    x = [[0,0,0,0,0,0,0,0,0,0,0,0,0]]
    result = mlp_model.predict(x)[0]
    print(result)
    print(f'耗时{time.perf_counter() - time1}')
    # 耗时0.00036s


def test2():
    time1 = time.perf_counter()
    new_mlp_model = joblib.load('saved_model_mlp.pkl')
    x = [[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3]]
    result = mlp_model.predict(x)[0]
    print(result)
    print(f'耗时{time.perf_counter() - time1}')


def predict():
    query = Drivinginfo.objects.all()[:10]
    query_value = query.values_list('car_speed', 'atmospheric_pressure',
                                    'actual_torque',
                                    'friction_torque', 'engine_speed',
                                    'fuel_flow', 'reactive_agent',
                                    'air_intake',
                                    'scr_inlet_temperature',
                                    'scr_outlet_temperature',
                                    'dpf_pressure_difference',
                                    'coolant_temperature', 'tank_level')
    # 单元素是一个元组，先转化为list再转化为二维数组
    x = [query_value[0]]
    global mlp_model
    result = mlp_model.predict(x)[0]
    print(result)


if __name__ == '__main__':
    start_time = time.perf_counter()
    # for i in range(10):
    #     test()
    #     #总耗时0.001秒
    # print(f'总耗时{time.perf_counter() - start_time}')
    # for i in range(10):
    #     test2()
    #     # 总耗时0.037秒，显然使用全局变量的速度更快
    # print(f'总耗时{time.perf_counter() - start_time}')
    # predict()
    test()
